<?php

namespace app\admin\controller\admin;

use app\common\controller\AdminController;
use app\common\services\annotation\ControllerAnnotation;
use app\common\services\annotation\NodeAnnotation;
use Juhelib\excel;
use PhpOffice\PhpSpreadsheet\IOFactory;
use support\Request;
use support\Response;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="activity_visitor")
 */
class ActivityVisitorController extends AdminController
{

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\ActivityVisitor();
    }

    /**
     * @NodeAnnotation(title="列表")
     */
    public function index(Request $request): Response
    {
        list($page, $limit, $where) = $this->buildTableParams();

        $activity_id = $request->get('activity_id');
        if (!$request->isAjax()) {
            return $this->fetch('', ['activityId' => $activity_id]);
        }
        if ($request->input('selectFields')) {
            return $this->selectList();
        }

        // 获取所有员工数据
        $clerk_user_ids = Db::name('activity_user_role')->where(['activity_id' => $activity_id, 'role' => 2])->column('user_id');

        $where[] = ['a.activity_id', '=', $activity_id];
        $count = $this->model
            ->alias('a')
            ->join('order o', 'a.order_id = o.id', 'left')
            ->join('user u', 'a.user_id = u.id', 'left')
            ->join('user cu', 'o.clerk_user_id = cu.id', 'left')
            ->join('user ru', 'o.recom_user_id = ru.id', 'left')
            ->field('a.*')
            ->where($where)->count();
        $list  = $this->model
            ->alias('a')
            ->join('order o', 'a.order_id = o.id', 'left')
            ->join('user u', 'a.user_id = u.id', 'left')
            ->join('user cu', 'o.clerk_user_id = cu.id', 'left')
            ->join('user ru', 'o.recom_user_id = ru.id', 'left')
            ->field('a.*')
            ->where($where)->order($this->order)->page($page, $limit)->select()->toArray();
        foreach ($list as &$value) {
            $data = Db::name('order')->where(['activity_id' => $value['activity_id'], 'user_id' => $value['user_id']])->find();
            $data['recom_nickname'] = Db::name('user')->where(['id' => $data['recom_user_id']])->value('nickname');
            $data['clerk_nickname'] = Db::name('user')->where(['id' => $data['clerk_user_id']])->value('nickname');
            // 销售数量
            $data['order_count'] = Db::name('order')->where(['activity_id' => $value['activity_id'], 'user_id' => $value['user_id'], 'order_status' => 2])->count();
            // 销售金额
            $data['order_total_price'] = Db::name('order')->where(['activity_id' => $value['activity_id'], 'user_id' => $value['user_id'], 'order_status' => 2])->sum('total_price');
            // 推荐奖励
            $data['payment_disburse_amount'] = Db::name('payment_disburse')
                ->where(['status' => 1, 'activity_id' => $value['activity_id'], 'user_id' => $value['user_id']])
                ->sum('amount');
            // 翻牌奖励
            $data['activity_prize_count'] = Db::name('payment_activity_prize')
                ->where(['activity_id' => $value['activity_id'], 'user_id' => $value['user_id']])
                ->count();
            // 平台盲盒
            $data['platform_box_prize_count'] = Db::name('payment_platform_box')
                ->where(['activity_id' => $value['activity_id'], 'user_id' => $value['user_id']])
                ->count();
            // 获取下单用户
            $user = Db::name('user')->where(['id' => $value['user_id']])->find();
            if (!empty($user)) {
                $data['avatar_url'] = $user['avatar_url'];
                $data['nickname'] = $user['nickname'];
                $data['openid'] = $user['openid'];
            }
            // 是否为员工直推
            $data['is_clerk_recom'] = in_array($data['recom_user_id'], $clerk_user_ids) ? 1 : 0;
            // 查询订单信息
            $data['order_info'] = Db::name('order')->where(['activity_id' => $value['activity_id'], 'user_id' => $value['user_id']])->field('name, phone, customer_type')->find();
            $value = array_merge($value, $data);
        }
        $data  = [
            'code'  => 0,
            'msg'   => '',
            'count' => $count,
            'data'  => $list,
        ];
        return json($data);
    }

    /**
     * @NodeAnnotation(title="修改上级/溯源员工")
     */
    public function relational(Request $request)
    {
        if (request()->isPost()) {
            $activity_id = $request->post('activity_id');
            $user_id = $request->post('user_id');
            $recom_user_id = $request->post('recom_user_id');
            $clerk_user_id = $request->post('clerk_user_id');

            if (empty($activity_id) && empty($user_id)) {
                $this->error('数据异常');
            }

            Db::startTrans();
            try {
                // 修改活动参与人员表
                Db::name('activity_visitor')->where(['activity_id' => $activity_id, 'user_id' => $user_id])->update(['recom_user_id' => $recom_user_id]);
                // 修改订单表
                Db::name('order')->where(['activity_id' => $activity_id, 'user_id' => $user_id])->update(['recom_user_id' => $recom_user_id, 'clerk_user_id' => $clerk_user_id]);

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return $this->error($e->getMessage());
            }
            return $this->success('修改成功');
        } else {
            $activity_id = $request->get('activity_id');
            $user_id = $request->get('user_id');

            // 获取订单信息
            $order = Db::name('order')->where(['activity_id' => $activity_id, 'user_id' => $user_id])->find();
            // 获取员工信息
            $clerk_user = Db::name('activity_user_role')
                ->alias('a')
                ->leftJoin('user b', 'a.user_id = b.id')
                ->where(['a.activity_id' => $activity_id, 'a.role' => 2])
                ->field('a.user_id, b.nickname')
                ->select()
                ->toArray();
            // 获取所有用户信息
            $user = Db::name('activity_user_role')
                ->alias('a')
                ->leftJoin('user b', 'a.user_id = b.id')
                ->where(['a.activity_id' => $activity_id])
                ->field('a.user_id, b.nickname')
                ->select();

            return $this->fetch('', [
                'activity_id' => $activity_id,
                'user_id' => $user_id,
                'clerk_user' => $clerk_user,
                'user' => $user,
                'recom_user_id' => $order['recom_user_id'],
                'clerk_user_id' => $order['clerk_user_id'],
            ]);
        }
    }

    /**
     * @NodeAnnotation(title="详情")
     */
    public function info(Request $request): Response
    {
        return $this->fetch('', [
            'activity_id' => $request->input('activity_id'),
            'user_id' => $request->input('user_id'),
        ]);
    }

    /**
     * @NodeAnnotation(title="直推人员")
     */
    public function direct_recom(Request $request): Response
    {
        $activity_id  = (int)$request->input('activity_id');
        $user_id  = (int)$request->input('user_id');
        $row = $this->model->where(['user_id' => $user_id, 'activity_id' => $activity_id])->find();
        list($page, $limit) = $this->buildTableParams();
        $count = Db::name('order')
            ->alias('a')
            ->join('user b', 'a.user_id = b.id', 'left')
            ->where(['a.activity_id' => $row['activity_id'], 'a.recom_user_id' => $row['user_id']])
            ->field('a.*, b.avatar_url, b.nickname, b.openid')
            ->count();
        $list  = Db::name('order')
            ->alias('a')
            ->join('user b', 'a.user_id = b.id', 'left')
            ->where(['a.activity_id' => $row['activity_id'], 'a.recom_user_id' => $row['user_id']])
            ->field('a.*, b.avatar_url, b.nickname, b.openid')
            ->order($this->order)->page($page, $limit)->select()->toArray();
        $data  = [
            'code'  => 0,
            'msg'   => '',
            'count' => $count,
            'data'  => $list,
        ];
        return json($data);
    }

    /**
     * @NodeAnnotation(title="导出")
     */
    public function export(Request $request): Response|bool
    {
        try {
            list($page, $limit, $where) = $this->buildTableParams();

            $activity_id = $request->get('activity_id');
            $where[] = ['a.activity_id', '=', $activity_id];

            // 获取所有员工数据
            $clerk_user_ids = Db::name('activity_user_role')->where(['activity_id' => $activity_id, 'role' => 2])->column('user_id');

            $list  = $this->model
                ->alias('a')
                ->join('order o', 'a.order_id = o.id', 'left')
                ->join('user u', 'a.user_id = u.id', 'left')
                ->join('user cu', 'o.clerk_user_id = cu.id', 'left')
                ->join('user ru', 'o.recom_user_id = ru.id', 'left')
                ->field('a.*')
                ->where($where)->order($this->order)->select()->toArray();
            foreach ($list as $key => $value) {
                $data = Db::name('order')->where(['activity_id' => $value['activity_id'], 'user_id' => $value['user_id']])->find();
                $data['recom_nickname'] = Db::name('user')->where(['id' => $data['recom_user_id']])->value('nickname');
                $data['clerk_nickname'] = Db::name('user')->where(['id' => $data['clerk_user_id']])->value('nickname');
                // 销售数量
                $data['order_count'] = Db::name('order')->where(['activity_id' => $value['activity_id'], 'user_id' => $value['user_id'], 'order_status' => 2])->count();
                // 销售金额
                $data['order_total_price'] = Db::name('order')->where(['activity_id' => $value['activity_id'], 'user_id' => $value['user_id'], 'order_status' => 2])->sum('total_price');
                // 推荐奖励
                $data['payment_disburse_amount'] = Db::name('payment_disburse')
                    ->where(['status' => 1, 'activity_id' => $value['activity_id'], 'user_id' => $value['user_id']])
                    ->sum('amount');
                // 翻牌奖励
                $data['activity_prize_count'] = Db::name('payment_activity_prize')
                    ->where(['activity_id' => $value['activity_id'], 'user_id' => $value['user_id']])
                    ->count();
                // 平台盲盒
                $data['platform_box_prize_count'] = Db::name('payment_platform_box')
                    ->where(['activity_id' => $value['activity_id'], 'user_id' => $value['user_id']])
                    ->count();
                // 获取下单用户
                $user = Db::name('user')->where(['id' => $value['user_id']])->find();
                if (!empty($user)) {
                    $data['avatar_url'] = $user['avatar_url'];
                    $data['nickname'] = $user['nickname'];
                    $data['openid'] = $user['openid'];
                }

                // 是否为员工直推
                $data['is_clerk_recom'] = in_array($data['recom_user_id'], $clerk_user_ids) ? 1 : 0;

                $data['order_info'] = Db::name('order')->where(['activity_id' => $value['activity_id'], 'user_id' => $value['user_id']])->field('name, phone, customer_type')->find();
                $value = array_merge($value, $data);

                $excelData[$key] = [
                    $value['nickname'] ?? '', $value['openid'] ?? '', $value['order_info']['name'] ?? '', $value['order_info']['phone'] ?? '', $value['order_info']['customer_type'] ?? '', ($value['is_clerk_recom'] == 1 ? "员工直推" : "非直推"),
                    $value['order_sn'] ?? '', $value['pay_no'] ?? '', $value['total_price'] ?? '', ($value['order_status'] ?? '' == 2 ? "已支付" : "未支付"),
                    $value['payment_disburse_amount'] ?? '', $value['activity_prize_count'] ?? '', $value['platform_box_prize_count'] ?? '',
                    $value['recom_nickname'] ?? '', $value['clerk_nickname'] ?? '', $value['create_time'] ?? '',
                ];
            }
            $spreadsheet = excel::handleExcel([[
                'name' => '参与明细',
                'title' => [
                    '会员昵称', 'OPENID', '姓名', '手机号', '新客/老客', '员工直推/非直推',
                    '订单编号', '支付编号', '支付金额', '支付状态',
                    '推荐奖励', '翻牌奖励', '平台盲盒',
                    '上级', '溯源员工', '参与时间',
                ],
                'data' => $excelData ?? []
            ]], []);
            $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');

            $file_name = '参与明细';
            $file_path = runtime_path() . '/excel/' . $file_name . time() . '.' . mt_rand(100000, 999999) . '.xlsx';
            // 保存文件到 public 下
            @mkdir(runtime_path() . '/excel/');
            $writer->save($file_path);
            // 下载文件
            return response()->download($file_path, $file_name . '.xlsx');
        } catch (\Exception|\PhpOffice\PhpSpreadsheet\Exception$e) {
            return $this->error($e->getMessage());
        }
    }

}
